/**  
* @Title: ShopTransRecordController.java
* @Package com.lemon.controller.cityRun
* @Description: (一句话阐述):
* @author Ran_cc
* @date 2018年10月22日
* @version V1.0  
*/
package com.lemon.controller.cityRun;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.lemon.conf.MyException;
import com.lemon.conf.MyInterceptor.LoginRequired;
import com.lemon.conf.content.IdTypeHandler;
import com.lemon.conf.redis.RedisUtil;
import com.lemon.controller.BaseController;
import com.lemon.model.buy.PayTransfersResult;
import com.lemon.model.cityRun.CrShopSet;
import com.lemon.model.cityRun.CrShopUser;
import com.lemon.model.cityRun.CrShops;
import com.lemon.model.cityRun.CrSysOperate;
import com.lemon.model.cityRun.CrUserTransactionRecord;
import com.lemon.service.cityRun.CrShopUserService;
import com.lemon.service.cityRun.CrShopsService;
import com.lemon.service.cityRun.CrSysOperateService;
import com.lemon.service.cityRun.CrUserTransactionRecordService;
import com.lemon.utils.HttpUtil;
import com.lemon.utils.ReqResult;
import com.lemon.utils.StringUtil;
import com.lemon.utils.XMLUtils;
import com.lemon.utils.appPush.AppPush;
import com.lemon.utils.pay.PayUtil;

/**
 * <p>Title: ShopTransRecordController</p>
 * <p>Description: 
 * </p>
 * <p>Company: </p>
 * @author Ran_cc
 * @date 2018年10月22日
 * @版本 V 1.0 
 */
@RestController
@RequestMapping("/trans")
public class ShopTransRecordController extends BaseController {

	@Resource
	private CrUserTransactionRecordService tranService;
	@Resource
	private CrShopsService shopService;
	@Resource
	private CrShopUserService uService;
	@Resource
	private CrSysOperateService operateService;


	//获取全部记录
	@LoginRequired
	@RequestMapping("/getShopTransList")
	public ReqResult getShopTransList(@ModelAttribute CrUserTransactionRecord trans , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			CrShopUser u = (CrShopUser) request.getSession().getAttribute("user");
			long ri = IdTypeHandler.decode(u.getRuleId());
			String star = request.getParameter("startTime");
			String end = request.getParameter("endTime");
			StringBuffer buffer = new StringBuffer();

			if (StringUtil.isNotBlank(star) && StringUtil.isNotBlank(end)) {
				buffer.append(" and a.create_time >='");
				buffer.append(star);
				buffer.append("' and a.create_time <='");
				buffer.append(end);
				buffer.append("'");
			} else if (StringUtil.isNotBlank(star)) {
				buffer.append(" and a.create_time >='");
				buffer.append(star);
				buffer.append("'");
			} else if (StringUtil.isNotBlank(end)) {
				buffer.append(" and a.create_time <='");
				buffer.append(end);
				buffer.append("'");
			}

			String ty = request.getParameter("types");
			if (StringUtil.isNotBlank(ty)) {
				if ("1".equals(ty)) {
					buffer.append(" and a.tran_type = 1 and a.type = 2 ");
				} else if ("3".equals(ty)) {
					buffer.append(" and a.tran_type = 2 ");
				} else if ("2".equals(ty)) {
					buffer.append(" and a.tran_type = 3 ");
				} else if ("4".equals(ty)) {
					buffer.append(" and a.tran_type = 1 and a.type = 1 ");
				}
			}
			buffer.append(" and a.status != 0 ");
			//			if (u.getUserType() == 1) {
			//				buffer.append(" and a.type = 1 ");
			//			}
			String par = request.getParameter("isusetleft");
			if (StringUtil.isNotBlank(par)) {
				buffer.append(" and (a.tran_type = 2  or a.tran_type = 1 ) ");
			}
			trans.setWhere(buffer.toString());

			trans.setOrderBy(" order by a.create_time desc");
				//查询管理员列表
				List<CrUserTransactionRecord> list = tranService.selectListBySelective(trans);
				reqResult.setReturnResult(list);
			//			}
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 修改提现管理
	 * </blockquote></b>
	 * 
	 * @Title: addAdminUserInfo
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年10月18日
	 */
	@LoginRequired
	@RequestMapping(value = "/updateShopTranInfo.do")
	public ReqResult updateShopTranInfo(@ModelAttribute CrUserTransactionRecord tran , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			log.info("开始处理提现管理信息:status={},shopId={}" , tran.getStatus() , tran.getShopId());

			CrUserTransactionRecord tr = tranService.selectById(tran.getId());
			CrShopUser user = null;
			if (tr != null) {
				user = uService.selectById(tr.getShopUserId());
			}

			int tt = 1;
			String ids = request.getParameter("remAllIds");
			String ids2 = request.getParameter("ids");
			if (StringUtil.isNotBlank(ids)) {
				tt = 1;
			} else if (StringUtil.isNotBlank(ids2)) {
				ids = ids2;
				tt = 2;
			}
			//批量同意提现
			if (StringUtil.isNotBlank(ids)) {
				if (tt == 1) {
					tran.setStatus(0);
				} else {
					tran.setStatus(1);
				}
				String[] split = ids.split(",");
				for (int i = 0; i < split.length; i++) {
					String id = split[i];
					tran.setId(id);
					int status = 0;
					if (tt == 2) {
						tr = tranService.selectById(tran.getId());
						if (tr != null) {
							PayTransfersResult payResult = PayUtil.transfers(tr.getShopUserWx() , "提现" ,
									tr.getAmountArrival() ,
									tr.getSerialNumber() , HttpUtil.getUsrIPAddr(request));
							if (payResult.isSuccess()) {//成功
								status = 2;
							} else {//去查询 //如果未成功 则抛出异常 成功 未知 需要 继续查询
								if (payResult.getErrCode().equals("NOTENOUGH")) {
									reqResult.setReturnResult("商户账户余额不足" , ReqResult.code_objecr_number);
									return reqResult;
								}

								status = 0;
								if (payResult.getErrCode().equals("SEND_FAILED")
										|| payResult.getErrCode().equals("SYSTEMERROR")) {
									status = 1;
									payResult = PayUtil.getTransferinfo(tr.getSerialNumber());
									if (payResult.isSuccess()) {
										status = 2;
									} else {
										if ("FAILED".equals(payResult.getStatus())) {
											status = 0;
											// userDao.addUserBurse(userId, amount);
										}
									}
								}
							}
						}

					if (status == 2) {
						int row = tranService.updateShopTranInfo(tran);
						reqResult.setReturnResult(1);
							try {
								String shopUserId = tr.getShopUserId();
								CrShopUser shopUser = uService.selectById(shopUserId);
								//往app推送提现消息
								AppPush push = new AppPush();
								push.setCid(shopUser.getCid());
								push.setTitle("提现成功");
								push.setType(4);
								DecimalFormat df = new DecimalFormat("0.00");
								String format = df.format(tr.getAmountArrival() / 100);
								push.setText("到账 " + format + " 元,点击查看");
								AppPush.pushMsgToSingle(push);
							} catch (Exception e) {
								MyException.writeErr(e , "推送提现消息失败");
							}
						}
					}
				}
				reqResult.setReturnResult("1");
				return reqResult;
			}
			//////////////////////////////////////
			//单个同意提现
			Integer status2 = tran.getStatus();
			if (status2 == 1) {

				int status = 0;
				if (tr != null) {
					PayTransfersResult payResult = PayUtil.transfers(user.getUserWx() , "提现" , tr.getAmountArrival() ,
							tr.getSerialNumber() , HttpUtil.getUsrIPAddr(request));
					if (payResult.isSuccess()) {//成功
						status = 2;

					} else {//去查询 //如果未成功 则抛出异常 成功 未知 需要 继续查询
						if (payResult.getErrCode().equals("NOTENOUGH")) {
							reqResult.setReturnResult("商户账户余额不足" , ReqResult.code_objecr_number);
							return reqResult;
						}
						status = 0;
						if (payResult.getErrCode().equals("SEND_FAILED")
								|| payResult.getErrCode().equals("SYSTEMERROR")) {
							status = 1;
							payResult = PayUtil.getTransferinfo(tr.getSerialNumber());
							if (payResult.isSuccess()) {
								status = 2;

							} else {
								if ("FAILED".equals(payResult.getStatus())) {
									status = 0;
								}
							}
						}
					}
				}
				if (status != 2) {
					reqResult.setReturnResult("提现失败,请联系账户管理人员" , ReqResult.code_objecr_number);
					return reqResult;
				}
				int row = tranService.updateShopTranInfo(tran);
				try {
					CrSysOperate operate = new CrSysOperate();
					operate.setAmount(-tran.getAmountArrival());
					operateService.updateOperateInfo(operate);
				} catch (Exception e) {
					MyException.writeErr(e , "");
				}
				reqResult.setReturnResult(1);
				try {
					String shopUserId = tr.getShopUserId();
					CrShopUser shopUser = uService.selectById(shopUserId);
					//往app推送提现消息
					AppPush push = new AppPush();
					push.setCid(shopUser.getCid());
					push.setTitle("提现成功");
					push.setType(4);
					DecimalFormat df = new DecimalFormat("0.00");
					String format = df.format(tr.getAmountArrival() / 100);
					push.setText("到账 " + format + " 元,点击查看");
					AppPush.pushMsgToSingle(push);
				} catch (Exception e) {
					MyException.writeErr(e , "推送提现消息失败");
				}
			} else {
				log.info("拒绝提现");
				try {
					int row = tranService.updateShopTranInfo(tran);
					reqResult.setReturnResult(1);
					String shopUserId = tr.getShopUserId();
					CrShopUser shopUser = uService.selectById(shopUserId);
					//往app推送提现消息
					AppPush push = new AppPush();
					push.setCid(shopUser.getCid());
					push.setTitle("提现失败");
					push.setType(4);
					DecimalFormat df = new DecimalFormat("0.00");
					String format = df.format(tr.getAmountArrival() / 100.0);
					push.setText("提现被拒绝,金额已返还账户,点击查看");
					AppPush.pushMsgToSingle(push);
				} catch (Exception e) {
					MyException.writeErr(e , "推送提现消息失败");
				}
			}
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}
	
	/**
	 * <b>Description:<blockquote> 新增提现交易记录
	 * </blockquote></b>
	 * 
	 * @Title: addAdminUserInfo
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年10月18日
	 */
	@LoginRequired
	@RequestMapping(value = "/addShopTranInfo.do" , method = RequestMethod.POST)
	public ReqResult addShopTranInfo(@ModelAttribute CrUserTransactionRecord tran , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			CrShopUser uu = (CrShopUser) request.getSession().getAttribute("user");
			String userid = uu.getId();
			if (StringUtil.isNotBlank(tran.getShopUserId())) {
				userid = tran.getShopUserId();
			}
			CrShops cs = new CrShops();
			//			cs.setShopUserId(userid);
			String sid = request.getParameter("shopId");
			if (StringUtil.isEmpty(sid)) {
				reqResult.setReturnResult("" , ReqResult.code_error);
				return reqResult;
			}
			cs.setId(sid);
			CrShops shops = shopService.selectShopAndUserBySel(cs);

			CrShopUser u = uService.selectById(shops.getShopUserId());
			if (u.getAmount() < tran.getAmount()) {
				reqResult.setReturnResult("" , ReqResult.code_not_exist);
				return reqResult;
			}
			tran.setSerialNumber(StringUtil.createSerialNoCityRun());
			tran.setStatus(3);
			tran.setAmount(tran.getAmount());
			//读取xml文件获取 提现手续费率
			String string = RedisUtil.get(RedisUtil.key_before + "setting");
			JSONObject js = ((JSONObject) JSONObject.parse(string)).getJSONObject("sets")
					.getJSONObject("enchenchashment");
			Integer sc = js.getInteger("serviceCharge"); //手续费
			Integer minAmount = js.getInteger("minAmount"); //最低提现金额
			if (tran.getAmount() < minAmount) {
				reqResult.setReturnResult("低于最低提现金额,请重新输入" , ReqResult.code_objecr_number);
				return reqResult;
			}
			//获取个人提现手续费的设置
			String sset = RedisUtil.get("cityRun:set:set_" + sid);
			System.out.println(sset);
			if (StringUtil.isNotBlank(sset)) {
				JSONObject jset = ((JSONObject) JSONObject.parse(sset));
				if (null != jset && jset.containsKey("serviceCharge") && 0 != jset.getInteger("serviceCharge")) {
					sc = jset.getInteger("serviceCharge");
				}
			}
			//
			log.info("手续费点:{}" , sc);
			int ss = (tran.getAmount() * sc) / 10000;
			log.info("提现金额:{},手续费:{},到账:{}" , tran.getAmount() , ss , (tran.getAmount() - ss));
			tran.setAmountLeft(u.getAmount());
			tran.setAmountArrival(tran.getAmount() - ss); //这里的3是提现设置里面的 百分之三   因为数据库存入的金额都是  分单位
			tran.setShopAccount(shops.getUserAccount());
			tran.setShopTitle(shops.getShopTitle());
			tran.setShopUserId(shops.getShopUserId());
			tran.setShopUserWx(u.getUserWx());
			tran.setTranType(2);
			tran.setType(1);
			int row = tranService.insertShopTranInfo(tran);
			reqResult.setReturnResult(row);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 设置体现手续费和体现说明信息
	 * </blockquote></b>
	 * 
	 * @Title: addAdminUserInfo
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年10月18日
	 */
	@LoginRequired
	@RequestMapping(value = "/addShopTranSet.do" , method = RequestMethod.POST)
	public ReqResult addShopTranSet(HttpServletRequest request , HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			String minAmount = request.getParameter("minAmount");
			String serviceCharge = request.getParameter("serviceCharge");
			String enchInfo = request.getParameter("enchInfo");
			if (StringUtil.isNotBlank(enchInfo)) {
				enchInfo = enchInfo.replace("\"" , "'");
			}

			String string = RedisUtil.get(RedisUtil.key_before + "setting");
			if (StringUtil.isEmpty(string)) {
				JSONObject parse = new JSONObject();
				JSONObject js = new JSONObject();
				JSONObject js2 = new JSONObject();
				js2.put("minAmount" , minAmount);
				js2.put("serviceCharge" , serviceCharge);
				js2.put("enchInfo" , enchInfo);
				js.put("enchenchashment" , js2);
				parse.put("sets" , js);
				RedisUtil.set(RedisUtil.key_before + "setting" , parse);
				XMLUtils.saveXml(parse.toJSONString() , XMLUtils.setUrl);
				reqResult.setReturnResult(1);
			}
			JSONObject parse = (JSONObject) JSONObject.parse(string);
			JSONObject js = parse.getJSONObject("sets");
			JSONObject js2 = js.getJSONObject("enchenchashment");
			js2.put("minAmount" , minAmount);
			js2.put("serviceCharge" , serviceCharge);
			js2.put("enchInfo" , enchInfo);
			js.put("enchenchashment" , js2);
			parse.put("sets" , js);
			RedisUtil.set(RedisUtil.key_before + "setting" , parse);
			XMLUtils.saveXml(parse.toJSONString() , XMLUtils.setUrl);
			reqResult.setReturnResult(1);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote>系统设置体现手续费以及体现说明
	 * </blockquote></b>
	 * 
	 * @Title: addAdminUserInfo
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年10月18日
	 */
	@RequestMapping(value = "/getShopTranSet" , method = RequestMethod.POST)
	public ReqResult getShopTranSet(HttpServletRequest request , HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			String string = RedisUtil.get(RedisUtil.key_before + "setting");
			JSONObject js = ((JSONObject) JSONObject.parse(string)).getJSONObject("sets");

			JSONObject js2 = js.getJSONObject("enchenchashment");
			JSONObject js3 = js.getJSONObject("sysSet");
			js2.put("platPhone" , js3.get("platPhone"));
			reqResult.setReturnResult(js2);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	@RequestMapping(value = "/updateShopSets" , method = RequestMethod.POST)
	public ReqResult updateShopSets(@ModelAttribute CrShops shops , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {

			tranService.updateShopSet(shops);
			//List<CrShops> list = tranService.selectShopSetList(shops);
			//修改缓存中的数据
			CrShopSet shop2 = new CrShopSet();
			shop2.setShopId(shops.getId());
			CrShopSet set = shopService.selectShopSetByShopId(shop2);
			if (null == set) {
				set = new CrShopSet();
				set.setShopId(shops.getId());
				shopService.insertShopSetInfo(set);
			}
			set = shopService.selectShopSetByShopId(shop2);
			RedisUtil.set("cityRun:set:set_" + shops.getId() , set);
			reqResult.setReturnResult(1);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}
	@RequestMapping(value = "/getShopSets" , method = RequestMethod.POST)
	public ReqResult getShopSets(@ModelAttribute CrShops shops , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {

			String star = request.getParameter("startTime");
			String end = request.getParameter("endTime");
			StringBuffer buffer = new StringBuffer();

			if (StringUtil.isNotBlank(star) && StringUtil.isNotBlank(end)) {
				buffer.append(" and a.create_time >='");
				buffer.append(star);
				buffer.append("' and a.create_time <='");
				buffer.append(end);
				buffer.append("'");
			} else if (StringUtil.isNotBlank(star)) {
				buffer.append(" and a.create_time >='");
				buffer.append(star);
				buffer.append("'");
			} else if (StringUtil.isNotBlank(end)) {
				buffer.append(" and a.create_time <='");
				buffer.append(end);
				buffer.append("'");
			}
			shops.setWhereAppend(buffer.toString());
			shops.setOrderBy(" order by a.create_time desc");
			List<CrShops> list = tranService.selectShopSetList(shops);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}
	/**
	 * <b>Description:<blockquote> 获取所有商家可提现 和已提现金额
	 * </blockquote></b>
	 * 
	 * @Title: getShopTranProfit
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月6日
	 */
	@RequestMapping(value = "/getShopProfit")
	public ReqResult getShopTranProfit(@ModelAttribute CrUserTransactionRecord tran , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			Map<String , Object> list = tranService.getShopTranProfit(tran);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	@RequestMapping(value = "/getShopTranDoing")
	public ReqResult getShopTranDoing(HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			Map<String , Object> list = tranService.getShopTranDoing();
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "查询客户或管理员列表失败");
		}
		return reqResult;
	}

	public static void main(String[] args) {
		DecimalFormat df = new DecimalFormat("0.00");
		int dd = 3;
		System.err.println(new DecimalFormat("0.00").format((dd / 100)));
	}

}
